package com.yjz.jvm.java8.Consumer_Function_Predicate_Supplier;

import org.junit.Assert;
import org.junit.Test;

import java.util.Optional;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;

/**
 * @Desc
 * @Author: jinzhong.yuan
 * @Date: 2019/2/18 10:38
 */
public class TestClassJava8Test {

    @Test
    public void java8Test() {
        TestClass testClass = new TestClass();
        //等于定义了一个函数(函数定义好了,并没有执行)
        Consumer<String> consumer = (x) -> System.out.println(x);
        // 执行一个函数
        consumer.accept("111");


        Consumer<Integer> consumer1 = x -> {
            int a = x + 2;
            System.out.println(a);// 12
            System.out.println(a + "_");// 12_
        };
        consumer1.accept(10);


        Function<String, String> function = testClass::bbb;
        String response = function.apply("222");
        System.out.println(response);

        User user = new User();
        System.out.println(getUserName(user));

    }


    /**
     * j8 optional用法
     *
     * @param user
     * @return
     */
    public String getUserName(User user) {
        //user对象不等于空，则进行一个 Consumer 操作
        Optional.ofNullable(user).ifPresent(u -> System.out.println(u));
        //避免了不好看的null判断
        return Optional.ofNullable(user)
                .map(User::getName)
                .orElse("unknown");
    }

    @Test
    public void consumerTest() {

        //定义一个consumerA
        Consumer<String> consumerA = s -> System.out.println(s);

        //定义一个consumerB
        Consumer<String> consumerB = X -> System.out.println(X);

        //执行consumerA的accept方法
        consumerA.accept("AA");

        //执行consumerB的accept方法
        consumerB.accept("BB");


        //俩个consumer包装成一个新的consumerC
        Consumer<String> consumerC = consumerA.andThen(consumerB);

        //执行consumerC的accept方法,内部会先执行前面的consumer,后执行后面的consumer
        consumerC.accept("CC");
    }


    @Test
    public void supplierTest() {
        // define a Supplier
        Supplier<String> supplier = () -> "张三";

        //call method get
        System.out.println(supplier.get());

    }

    @Test
    public void predicateTest() {
        //define a Predicate with one condition
        Predicate<String> predicate = s -> s.contains("a");

        //call method test
        Assert.assertTrue(predicate.test("apple"));

        //define an other predicate whit two condition :  string contains 'a'   or the length of string gte 10
        Predicate<String> predicateB = predicate.or(s -> s.length() > 10);

        Assert.assertTrue(predicateB.test("apple"));

        // 定义一个新的predicate, with 2个 并列条件  string contains 'a'   and the length of string gte 10
        Predicate<String> predicateC = predicate.and(s -> s.length() > 10);

        // predicateC.test会执行失败
        Assert.assertFalse(predicateC.test("apple"));
    }


}
